package com.demo.service.app.service.impl;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.service.app.dao.TabCloudDao;
import com.demo.service.app.pojo.TabCloud;
import com.demo.service.app.service.TabCloudService;
import com.demo.service.app.util.SnowFlake;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

@Service
@Slf4j
public class TabCloudServiceImpl implements TabCloudService {

	@Resource
	private TabCloudDao tabCloudDao;
	
	@Override
	public int add(TabCloud tabCloud) {
		tabCloud.setCreateTime(LocalDateTime.now());
		return tabCloudDao.add(tabCloud);
	}
	@Override
	@Transactional
	public int batchAdd() {
		SnowFlake snowFlake = new SnowFlake(2, 3);
		List<TabCloud> tabCloudList = new ArrayList<TabCloud>();
		
		String baseUrl = "";
		Document doc = null;
		try {
			doc = Jsoup.connect(baseUrl).get();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		Element content = doc.getElementsByClass("tagcloud").first();
		
		Elements links = content.getElementsByTag("a");
		for (Element link : links) {
			TabCloud tabCloud = new TabCloud();
			
			String tabName = link.text();
			String tabLink = link.attr("href");
			
			tabCloud.setId(String.valueOf(snowFlake.nextId()));
			tabCloud.setName(tabName);
			tabCloud.setLink(tabLink);
			tabCloud.setCreateTime(LocalDateTime.now());
			//组装成列表
			tabCloudList.add(tabCloud);
		}
		
		tabCloudDao.deleteAll();
		tabCloudDao.batchAdd(tabCloudList);
		
		return 0;
	}

}
